package cn.tohsaka.factory.dockercraft.utils;

import cn.tohsaka.factory.dockercraft.Utils;
import org.webbitserver.HttpControl;
import org.webbitserver.HttpHandler;
import org.webbitserver.HttpRequest;
import org.webbitserver.HttpResponse;

import java.io.File;
import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Xmsoft on 2016/8/4.
 */
public class sessions implements HttpHandler {
    static Map<String, session> sss = new HashMap();

    @Override
    public void handleHttpRequest(HttpRequest req, HttpResponse res, HttpControl rec) throws Exception {
        File path = new File(System.getProperty("user.dir") + File.separator + "sessions");
        while (!path.exists()) {
            path.mkdirs();
        }
        String ssid = req.cookieValue("sessid");
        if (ssid == null) {
            ssid = Utils.getRandomString(16);
            HttpCookie cookie = new HttpCookie("sessid", ssid);
            cookie.setPath("/");
            cookie.setMaxAge(2600000);
            req.cookies().add(cookie);
            res.cookie(cookie);
        }
        sss.put(ssid, new session(ssid));
        rec.nextHandler();
    }

    public static session get(String ssid) {
        return sss.get(ssid);
    }

    public static session get(HttpRequest req) {
        return get(req.cookieValue("sessid"));
    }
}
